#include "headfiles.h"

using namespace std;

bool addNode(NODE *root, NODE *n, unsigned int loc, int d)
{
	if (root == n) {
		root->left = NULL;
		root->right = NULL;
		root->p = NULL;
		return true;
	}

	if (root == NULL || n == NULL) {
		cout << "Input pointer NULL" << endl;
		return false;
	}
		
	bool is_left;
	NODE *child = root;
	int i;
	for (i = 0; i < d - 2; i++) {
		is_left = loc & 1;
		loc = loc >> 1;
		if (child == NULL) {
			return false;
		}

		if (is_left) {
			child = child->left;
		}
		else {
			child = child->right;
		}
	}

	is_left = loc & 1;
	if (child == NULL) {
		return false;
	}
	if (is_left) {
		child->left = n;
		n->p = child;
	}
	else {
		child->right = n;
		n->p = child;
	}

	return true;
}

NODE * createBinaryTree(char* file_name)
{
	fstream nf;
	nf.open(file_name, fstream::in);
	if (!nf.is_open()) {
		cout << "File " << file_name << " open error!\n" << endl;
		return NULL;
	}

	string str;
	NODE *node, *root = NULL;
	int node_val, loc, depth;

	while (nf >> str) {
		if (str.empty()) {
			return root;
		}

		node_val = atoi(str.c_str());
		nf >> str;
		loc = atoi(str.c_str());
		nf >> str;
		depth = atoi(str.c_str());

		cout << "Node value is: " << node_val;
		cout << "		loc is: " << loc;
		cout << "		depth is: " << depth << endl;

		node = (NODE *) malloc(sizeof(NODE));
		if (node == NULL) {
			cout << "Allocate node buffer error, NULL" << endl;
			return root;
		}

		node->left = NULL;
		node->right = NULL;
		node->p = NULL;
		node->i = node_val;
		if (root == NULL) {
			root = node;
		}

		addNode(root, node, loc, depth);
	}

	nf.close();

	return root;
}


NODE * createBinaryTreeAll(char* file_name, NODE ** & node_list, int &node_num)
{
	fstream nf;
	nf.open(file_name, fstream::in);
	if (!nf.is_open()) {
		cout << "File " << file_name << " open error!\n" << endl;
		return NULL;
	}

	// Allocate an array for all nodes
	node_list = (NODE **)malloc(sizeof(NODE *) * 1000);
	if (node_list == NULL) {
		cout << "Allocate array for node list pointer error!" << endl;
		return NULL;
	}
	node_num = 0;

	string str;
	NODE *node, *root = NULL;
	int node_val, loc, depth;

	while (nf >> str) {
		if (str.empty()) {
			return root;
		}

		node_val = atoi(str.c_str());
		nf >> str;
		loc = atoi(str.c_str());
		nf >> str;
		depth = atoi(str.c_str());

		cout << "Node value is: " << node_val;
		cout << "		loc is: " << loc;
		cout << "		depth is: " << depth << endl;

		node = (NODE *) malloc(sizeof(NODE));
		if (node == NULL) {
			cout << "Allocate node buffer error, NULL" << endl;
			return root;
		}
		node_list[node_num] = node;
		node_num++;

		node->left = NULL;
		node->right = NULL;
		node->p = NULL;
		node->i = node_val;
		if (root == NULL) {
			root = node;
		}

		addNode(root, node, loc, depth);
	}

	nf.close();

	return root;
}


